package com.maxima.attendance.actions;

import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;

import com.maxima.attendance.daos.AdminDAO;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport implements SessionAware {
	private static final long serialVersionUID = 1L;
	private String username;
	private String password;
	private Map<String, Object> map;
	// for logging
	static Logger logger = Logger.getLogger(ProjectAction.class.getName());

	@Override
	public String execute() throws Exception {
		if (SessionManager.validateAdminSession()) {
			return "admin";
		} else if (SessionManager.validateUserSession()) {
			return "user";
		} else {
			return ERROR;
		}
	}

	public String login() {
		this.password = ServletActionContext.getRequest().getParameter("password");
		this.username = ServletActionContext.getRequest().getParameter("username");
		if (ServletActionContext.getRequest().getParameter("usertype").equals("admin")) {
			return adminLogin() ? "admin" : ERROR;
		} else if (this.username != null && this.username.equals("Administrator")) {
			return adminLogin() ? "admin" : ERROR;
		} else {
			return userLogin() ? "user" : ERROR;
		}
	}

	public String logout() {
		logger.info(map.get(SessionManager.ACTIVE_LOGIN) + " " + " Logout Successfully");
		SessionManager.clearSession();
		return SUCCESS;
	}

	private boolean userLogin() {
		if (username != null && password != null) {
			if (new AdminDAO().checkLogin(username, password)) {
				map.put(SessionManager.USER_LOGIN, true);
				map.put(SessionManager.ACTIVE_LOGIN, username);
				this.setSession(map);
				logger.info(map.get(SessionManager.ACTIVE_LOGIN) + " " + " Login Successfully");
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	private boolean adminLogin() {
		if (password != null) {
			if (new AdminDAO().checkLogin("Administrator", password)) {
				map.put(SessionManager.ACTIVE_LOGIN, "Administrator");
				map.put(SessionManager.ADMIN_LOGIN, true);
				this.setSession(map);
				logger.info(map.get(SessionManager.ACTIVE_LOGIN) + " " + " Login Successfully");
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	@Override
	public void setSession(Map<String, Object> map) {
		this.map = map;
	}
}
